package com.hooda.server;

import com.hooda.container.Context;
import com.hooda.container.Engine;
import com.hooda.container.Service;
import com.hooda.servlet.HttpServlet;

import java.io.IOException;
import java.net.Socket;

/**
 * @author zhangzp
 * @version 1.0, 2021/10/11
 */
public class RequestProcessor extends Thread {

    private Socket socket;
    private Engine engine;

    public RequestProcessor(Socket socket, Engine engine) {
        this.socket = socket;
        this.engine = engine;
    }

    @Override
    public void run() {
        try {
            Request request = new Request(socket.getInputStream());
            Response response = new Response(socket.getOutputStream());

            String url = request.getUrl();
            if (url.startsWith("/")) {
                url = url.substring(1);
            }
            String contextName = "root";
            String urlPattern = request.getUrl();
            int index = url.indexOf("/");
            if (index > 0) {
                contextName = url.substring(0, index);
                urlPattern = url.substring(index);
            }

            request.setContextName(contextName);
            request.setUrlPattern(urlPattern);

            Context context = engine.getHost(request.getHost()).getContext(request.getContextName());
            request.setContext(context);

            HttpServlet httpServlet = context.getWrapper(request.getUrlPattern()).getServlet();
            if (httpServlet != null) {
                httpServlet.service(request, response);
            }
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
